package com.manage.competition.controller;

import com.manage.competition.common.ServerResponse;
import com.manage.competition.entity.*;
import com.manage.competition.service.ICompetitionService;
import com.manage.competition.vo.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Create with IDEA
 *
 * @Author: gitee.com/KamisamaXX
 * @Date: Create in 20:26 2019/3/24
 * @Description:
 */
@RestController
@RequestMapping("/competition")
public class CompetitionController {

    @Autowired
    private ICompetitionService competitionService;

    @RequiresRoles(value = {"user","admin"},logical = Logical.OR)
    @GetMapping("getCompetitionDetail")
    public ServerResponse<CompetitionDetailVo> getCompetitionDetail(long competitionId){
        return ServerResponse.createBySuccess(competitionService.getCompetitionDetail(competitionId));
    }

    @RequiresRoles(value = {"admin"})
    @GetMapping("getCurrentCompetitionDetail")
    public ServerResponse<CompetitionVo> getCurrentCompetitionDetail(){
        return ServerResponse.createBySuccess(competitionService.getCurrentCompetitionDetail());
    }

    @RequiresRoles(value = {"user","admin"},logical = Logical.OR)
    @GetMapping("getCompetitionList")
    public ServerResponse<List<CompetitionVo>> getCompetitionList(int status){
        return ServerResponse.createBySuccess(competitionService.findCompetitionListByStatus(status));
    }

    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @GetMapping("getAdvertisePicture")
        public ServerResponse<String> getAdvertisePicture(String type){
        return ServerResponse.createBySuccess(competitionService.getAdvertisePicture(type));
    }

    @RequiresRoles(value = {"admin"})
    @GetMapping("deleteAdvertisePicture")
    public ServerResponse<String> deleteAdvertisePicture(String type){
        if (competitionService.deleteAdvertisePicture(type)>0){
            return ServerResponse.createBySuccess("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @GetMapping("getSignUpInfo")
    public ServerResponse<SignUpInfoVo> getSignUpInfo(@RequestParam(required = false,defaultValue = "0") long id){
        if (id!=0){
            // TODO user传ID
        }
        return ServerResponse.createBySuccess(competitionService.getSignUpInfo());
    }

    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @GetMapping("getCompetitionInformation")
    public ServerResponse<CompetitionInformationVo> getCompetitionInformation(){
        return ServerResponse.createBySuccess(competitionService.getCompetitionInformation());
    }

    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @GetMapping("getContact")
    public ServerResponse<ContactVo> getContact(){
        return ServerResponse.createBySuccess(competitionService.getContact());
    }

    @RequiresRoles(value = {"admin","user"},logical = Logical.OR)
    @GetMapping("getOrganizer")
    public ServerResponse<OrganizerVo> getOrganizer(){
        return ServerResponse.createBySuccess(competitionService.getOrganizer());
    }

    @RequiresRoles(value = {"user","teacher","admin"},logical = Logical.OR)
    @GetMapping("getUserExaminationPaper")
    public ServerResponse<UserPaperVo> getUserExaminationPaper(
            long competitionId,
            @RequestParam(value = "userId",required = false) Long userId){
        return ServerResponse.createBySuccess(competitionService.getUserExaminationPaper(competitionId,userId));
    }

    @RequiresRoles(value = {"admin"})
    @GetMapping("getExaminationPaper")
    public ServerResponse<ExaminationPaperVo> getExaminationPaper(){
        return ServerResponse.createBySuccess(competitionService.getExaminationPaper());
    }

    @RequiresRoles(value = {"admin"})
    @GetMapping("getExaminationColumn")
    public ServerResponse<List<ExaminationColumnVo>> getExaminationColumn(long paperId){
        return ServerResponse.createBySuccess(competitionService.getExaminationColumn(paperId));
    }

    @RequiresRoles(value = {"admin"})
    @GetMapping("getExaminationQuestion")
    public ServerResponse<List<ExaminationQuestionVo>> getExaminationQuestion(long columnId){
        return ServerResponse.createBySuccess(competitionService.getExaminationQuestion(columnId));
    }

    @RequiresRoles(value = {"user"})
    @GetMapping("getEnrollList")
    public ServerResponse<List<CompetitionDetailVo>> getEnrollList(){
        return ServerResponse.createBySuccess(competitionService.getEnrollList());
    }

    @RequiresRoles(value = {"user"})
    @GetMapping("getUploadAnswer")
    public ServerResponse<String> getUploadAnswer(long questionId){
        String answer = competitionService.getUploadAnswer(questionId);
        return ServerResponse.createBySuccess(answer);
    }

    @RequiresRoles(value = {"teacher"})
    @GetMapping("getCompetitionReviewList")
    public ServerResponse<List<CompetitionDetailVo>> getCompetitionReviewList(){
        List<CompetitionDetailVo> detailVos = competitionService.getCompetitionReviewList();
        return ServerResponse.createBySuccess(detailVos);
    }

    @RequiresRoles(value = {"teacher"})
    @GetMapping("getEnrollUser")
    public ServerResponse<List<UserScoreVo> > getEnrollUser(long competitionId){
        List<UserScoreVo> enrollUsers = competitionService.getEnrollUser(competitionId);
        return ServerResponse.createBySuccess(enrollUsers);
    }

//    @RequiresRoles(value = {"admin"})
//    @GetMapping("getEnrollUserAndDetail")
//    public ServerResponse<List<UserScoreVo> > getEnrollUserAndDetail(long competitionId){
//        List<UserScoreVo> enrollUsers = competitionService.getEnrollUserAndDetail(competitionId);
//        return ServerResponse.createBySuccess(enrollUsers);
//    }

//    @RequiresRoles(value = {"teacher"})
//    @GetMapping("getCompetitionAnswerList")
//    public ServerResponse<List<UserAnswerVo>> getCompetitionAnswerList(long competitionId){
//        List<UserAnswerVo> detailVos = competitionService.getCompetitionAnswerList(competitionId);
//        return ServerResponse.createBySuccess(detailVos);
//    }

    @RequiresRoles(value = {"teacher"})
    @GetMapping("getScore")
    public ServerResponse<CompetitionScore> getScore(Long userId, Long questionId){
        CompetitionScore score = competitionService.getScore(userId,questionId);
        if (score!=null){
            return ServerResponse.createBySuccess(score);
        }
        return ServerResponse.createByErrorMessage("记录为空");
    }

    @RequiresRoles(value = {"admin"})
    @GetMapping("getGradeTeacher")
    public ServerResponse<List<String>> getGradeTeacher(){
        List<String> id = competitionService.getGradeTeacher();
        if (id!=null){
            return ServerResponse.createBySuccess(id);
        }
        return ServerResponse.createByErrorMessage("记录为空");
    }

    @RequiresRoles(value = {"user","admin"},logical = Logical.OR)
    @GetMapping("getCharts")
    public ServerResponse<List<ChartsVo>> getCharts(Long competitionId){
        List<ChartsVo>  charts = competitionService.getCharts(competitionId);
        if (charts!=null){
            return ServerResponse.createBySuccess(charts);
        }
        return ServerResponse.createByErrorMessage("记录为空");
    }

    @RequiresRoles(value = {"admin"},logical = Logical.OR)
    @GetMapping("getTeacherGrade")
    public ServerResponse<List<TeacherGradeVo>> getTeacherGrade(Long competitionId,Long userId,Long questionId){
        List<TeacherGradeVo> teacherGrade = competitionService.getTeacherGrade(competitionId,userId,questionId);
        if (teacherGrade!=null){
            return ServerResponse.createBySuccess(teacherGrade);
        }
        return ServerResponse.createByErrorMessage("记录为空");
    }


//    ------------------------------------------------------------------------------------------------------------------

    @RequiresRoles(value = {"admin"})
    @PostMapping("setCurrentCompetition")
    public ServerResponse<Long> setCurrentCompetition(Long name){
        competitionService.setCurrentCompetition(name);

        return ServerResponse.createBySuccess(name);
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("newCompetition")
    public ServerResponse<Long> newCompetition(){
        long result = competitionService.newCompetition();
        if (result==0){
            ServerResponse.createByErrorMessage("新建竞赛失败");
        }
        return ServerResponse.createBySuccess("新建竞赛成功",result);
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("endCompetition")
    public ServerResponse<String> endCompetition(Long id){
        if (id!=null){int i = competitionService.endCompetition(id);
            if(i>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("imageUpload")
    public ServerResponse<String> imageUpload(MultipartFile advertiseBig){
        String targetFileName="";
        if (advertiseBig!=null){
            targetFileName = competitionService.upload(advertiseBig,"big");
        }
        if (targetFileName==null){
            return ServerResponse.createByErrorMessage("文件上传失败");
        }
        return ServerResponse.createBySuccess(targetFileName);
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("fillItem")
    public ServerResponse<String> fillItem(@RequestParam(value = "title") String title,
                                           @RequestParam(value = "type") boolean type){
        if (competitionService.setFillItem(title,type)>0){
            return ServerResponse.createBySuccess("成功");
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("singleOption")
    public ServerResponse<String> singleOption(@RequestParam(value = "title") String title,
                                               @RequestParam(value = "options") String options,
                                               @RequestParam(value = "type") boolean type){
        if (competitionService.setSingleOption(title,options,type)>0){
            return ServerResponse.createBySuccess("成功");
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("doubleOption")
    public ServerResponse<String> doubleOption(@RequestParam(value = "title") String title,
                                               @RequestParam(value = "firstOptions") String firstOptions,
                                               @RequestParam(value = "secondOptions") String secondOptions,
                                               @RequestParam(value = "type") boolean type){
        if (competitionService.setDoubleOption(title,firstOptions,secondOptions,type)>0){
            return ServerResponse.createBySuccess("成功");
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("deleteOption")
    public ServerResponse<String> deleteOption(@RequestParam(value = "optionId") long optionId){
        if (competitionService.deleteOption(optionId)>0){
            return ServerResponse.createBySuccess("成功");
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setCompetitionInformation")
    public ServerResponse<String> setCompetitionInformation(
            @RequestParam(value = "name",required = false) String name,
            @RequestParam(value = "enrollStartDate",required = false) String enrollStartDate,
            @RequestParam(value = "enrollEndDate",required = false) String enrollEndDate,
            @RequestParam(value = "competitionStartDate",required = false) String competitionStartDate,
            @RequestParam(value = "competitionEndDate",required = false) String competitionEndDate,
            @RequestParam(value = "competitionIntroduction",required = false) String competitionIntroduction

    ){
        CompetitionInformation competitionInformation = new CompetitionInformation();
        competitionInformation.setName(name);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(enrollStartDate);competitionInformation.setEnrollStartDate(date);
            date = simpleDateFormat.parse(enrollEndDate);competitionInformation.setEnrollEndDate(date);
            date = simpleDateFormat.parse(competitionStartDate);competitionInformation.setCompetitionStartDate(date);
            date = simpleDateFormat.parse(competitionEndDate);competitionInformation.setCompetitionEndDate(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        competitionInformation.setCompetitionIntroduction(competitionIntroduction);

        if (competitionInformation.getName()!=null){
            if(competitionService.setCompetitionInformation(competitionInformation)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setContact")
    public ServerResponse<String> setContact(Contact contact){
        if (contact.getName()!=null){
            if(competitionService.setContact(contact)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setOrganizer")
    public ServerResponse<String> setOrganizer(@RequestParam(value = "sponsor",defaultValue = "")String sponsor,
                                               @RequestParam(value = "sponsor",required = false,defaultValue = "")String organizer,
                                               @RequestParam(value = "sponsor",required = false,defaultValue = "")String coOrganizer){
        Organizer or = new Organizer();
        if (sponsor!=null){
            or.setSponsor(sponsor);
        }
        if (organizer!=null){
            or.setOrganizer(organizer);
        }
        if (coOrganizer!=null){
            or.setCoOrganizer(coOrganizer);
        }
        if(competitionService.setOrganizer(or)>0){
            return ServerResponse.createBySuccess("成功");
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setExamPaper")
    public ServerResponse<String> setExamPaper(
            @RequestParam(value = "id",required = false) long id,
            @RequestParam(value = "title",required = false) String title,
            @RequestParam(value = "examStartDate",required = false) String examStartDate,
            @RequestParam(value = "examEndDate",required = false) String examEndDate,
            @RequestParam(value = "announceAnswer",required = false) String announceAnswer,
            @RequestParam(value = "examBackup",required = false) String examBackup,
            @RequestParam(value = "totalScore",required = false) Integer totalScore
    ){
        if (id > 0 && examStartDate!=null){
            ExaminationPaper paper = new ExaminationPaper();
            paper.setId(id);
            paper.setExamBackup(examBackup);
            paper.setTotalScore(totalScore);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = simpleDateFormat.parse(examStartDate);paper.setExamStartDate(date);
                date = simpleDateFormat.parse(examEndDate);paper.setExamEndDate(date);
                date = simpleDateFormat.parse(announceAnswer);paper.setAnnounceAnswer(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(competitionService.setExamPaper(paper)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }else if (title!=null && id>0){
            ExaminationPaper paper = new ExaminationPaper();
            paper.setId(id);
            paper.setTitle(title);
            if(competitionService.setExamPaper(paper)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("createExamColumn")
    public ServerResponse<String> createExamColumn(long paperId){
        if (paperId > 0){
            Long id = competitionService.createExamColumn(paperId);
            if(id!=null){
                return ServerResponse.createBySuccess(id.toString());
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setExamColumn")
    public ServerResponse<String> setExamColumn(ExaminationColumn column){
        if (column.getPaperId() > 0&& column.getId()>0){
            if(competitionService.setExamColumn(column)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("createExamQuestion")
    public ServerResponse<String> createExamQuestion(long columnId){
        if (columnId > 0 ){
            if(competitionService.createExamQuestion(columnId)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setExamQuestion")
    public ServerResponse<String> setExamQuestion(ExaminationQuestions questions){
        if (questions.getColumnId() > 0 && questions.getId()>0){
            if(competitionService.setExamQuestion(questions)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("deleteExamQuestion")
    public ServerResponse<String> deleteExamQuestion(ExaminationQuestions questions){
        if (questions.getColumnId() > 0 && questions.getId()>0){
            if(competitionService.deleteExamQuestion(questions)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("deleteExamColumn")
    public ServerResponse<String> deleteExamColumn(ExaminationColumn column){
        if (column.getPaperId() > 0&& column.getId()>0){
            if(competitionService.deleteExamColumn(column)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("publishCompetition")
    public ServerResponse<String> publishCompetition(long competitionId){
        if (competitionId > 0){
            if(competitionService.publishCompetition(competitionId)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("reEditCompetition")
    public ServerResponse<String> reEditCompetition(long competitionId){
        if (competitionId > 0){
            if(competitionService.reEditCompetition(competitionId)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"user"})
    @PostMapping("enrollCompetition")
    public ServerResponse<String> enrollCompetition(long competitionId){
        if (competitionId > 0){
            if(competitionService.enrollCompetition(competitionId)>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

//    @RequiresRoles(value = {"user"})
//    @PostMapping("enrollCompetitionMessage")
//    public ServerResponse<String> enrollCompetitionMessage(String vo){
//        if (vo != null){
//            ObjectMapper objectMapper = new ObjectMapper();
//            try {
//                List<String> list = objectMapper.readValue(vo, List.class);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            //            if(competitionService.enrollCompetitionMessage(vo)>0){
//    //                return ServerResponse.createBySuccess("成功");
////            }
//        }
//        return ServerResponse.createByErrorMessage("失败");
//    }

    @RequiresRoles(value = {"user"})
    @PostMapping("answerUpload")
    public ServerResponse<String> answerUpload(MultipartFile file,long competitionId,long paperId,long columnId,long questionId){
        if (file != null){
            String targetFile = competitionService.answerUpload(file,competitionId,paperId,columnId,questionId);
            if(targetFile!=null){
                return ServerResponse.createBySuccess(targetFile);
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"teacher"})
    @PostMapping("setScore")
    public ServerResponse<String> setScore(String score,Long userId,Long questionId, Long competitionId){
        if (userId != null&&score!=null&&questionId!=null){
            int i = competitionService.setScore(Integer.parseInt(score),userId,questionId,competitionId);
            if(i>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("setGradeTeacher")
    public ServerResponse<String> setGradeTeacher(GradeTeacherVo vo){
        if (vo!=null){int i = competitionService.setGradeTeacher(vo);
            if(i>0){
                return ServerResponse.createBySuccess("成功");
            }
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    @RequiresRoles(value = {"admin"})
    @PostMapping("deleteCompetition")
    public ServerResponse<String> deleteCompetition(Long competitionId){
        if (competitionService.deleteCompetition(competitionId)>0){
            return ServerResponse.createBySuccess("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }


}
